package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.example.springboot.entity.ComplainForm;
import com.example.springboot.entity.Notice;
import com.example.springboot.entity.RepairForm;
import com.example.springboot.entity.User;
import com.example.springboot.mapper.ComplainMapper;
import com.example.springboot.service.ComplainService;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.soap.Detail;
import java.util.List;

/**
 * 功能：投诉系统的增删改查
 * 作者：zhoujun
 * 日期： 2024/5/6 22:28
 */
@RestController
@RequestMapping("/complain")
public class ComplainController {
    @Autowired
    ComplainService complainService;

    @Autowired
    UserService userService;

    /**
     * 新增投诉
     */
    @HoneyLogs(operation = "投诉", type = LogType.ADD)
    @PostMapping("/add")
    public Result add(@RequestBody ComplainForm complainForm) {
        User currentUser = TokenUtils.getCurrentUser();  // 获取到当前登录的用户信息

        complainForm.setTime(DateUtil.now());  //   2023-09-12 21:09:12
       complainForm.setStatus("未处理");
        complainService.save(complainForm);
        return Result.success();
    }

    /**
     * 修改信息
     */
    @HoneyLogs(operation = "投诉", type = LogType.UPDATE)
    @PutMapping("/update")
    public Result update(@RequestBody ComplainForm complainForm) {

        complainService.updateById(complainForm);
        return Result.success();
    }

    /**
     * 删除信息
     */
    @HoneyLogs(operation = "投诉", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        complainService.removeById(id);
        return Result.success();
    }


    /**
     * 批量删除
     */
    @HoneyLogs(operation = "投诉", type = LogType.BATCH_DELETE)
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        complainService.removeBatchByIds(ids);
        return Result.success();
    }

    /**
     * 查询全部信息
     */
    @GetMapping("/selectAll")
    public Result selectAll() {
        List<ComplainForm> complainFormList = complainService.list(new QueryWrapper<ComplainForm>().orderByDesc("id"));
        return Result.success(complainFormList);
    }

    /**
     * 查询投诉订单表
     * @return 投诉表
     */
    @GetMapping("/selectUserData")
    public Result selectUserData() {
        QueryWrapper<ComplainForm> queryWrapper = new QueryWrapper<ComplainForm>().orderByDesc("id");
        queryWrapper.eq("open", 1); // 用户只能看到公开的公告数据
        List<ComplainForm> userList = complainService.list(queryWrapper);
        return Result.success(userList);
    }

    /**
     * 根据ID查询信息
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        ComplainForm complainForm = complainService.getById(id);
        User user = userService.getById(complainForm.getId());
        if (user != null) {
            complainForm.setUsername(user.getName());
        }
        return Result.success(complainForm);
    }



    /**
     * 多条件模糊查询信息
     * pageNum 当前的页码
     * pageSize 每页查询的个数
     */
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam String username) {
        QueryWrapper<ComplainForm> queryWrapper = new QueryWrapper<ComplainForm>().orderByDesc("id");  // 默认倒序，让最新的数据在最上面
        queryWrapper.like(StrUtil.isNotBlank(username), "username", username);
        Page<ComplainForm> page = complainService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<ComplainForm> records = page.getRecords();
//        List<User> list = userService.list();
        for (ComplainForm record : records) {
            Integer authorid = record.getId();
            User user = userService.getById(authorid);
//            String author = list.stream().filter(u -> u.getId().equals(authorid)).findFirst().map(User::getName).orElse("");
            if (user != null) {
                record.setUsername(user.getName());
            }
        }
        return Result.success(page);
    }

    @GetMapping("/selectFeedbackByPhone")
    public Result selectFeedbackByPhone(
            @RequestParam("phonenum") String phonenum,
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize) {

        QueryWrapper<ComplainForm> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phonenum", phonenum)
                .orderByDesc("time");

        Page<ComplainForm> page = complainService.page(new Page<>(pageNum, pageSize), queryWrapper);

        return Result.success(page);
    }


    @GetMapping("/selectByPages")
    public Result selectByPages(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(value = "username", required = false) String username) {

        User currentUser = TokenUtils.getCurrentUser();
        String currentUserName = currentUser.getUsername();


        QueryWrapper<ComplainForm> queryWrapper = new QueryWrapper<>();
        // 只查询当前用户的记录
        queryWrapper.eq("username", currentUserName); //user_phone 字段用于存储用户手机号

        // 如果提供了手机号参数，并且手机号不为空或空白，则添加手机号查询条件
        if (StrUtil.isNotBlank(username)) {
            queryWrapper.and(wrapper -> wrapper.like("username", username));
        }

        // 分页查询
        IPage<ComplainForm> page = complainService.page(new Page<>(pageNum, pageSize), queryWrapper);

        // 返回分页结果
        return Result.success(page);
    }





}